<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-05-26
 * Time: 10:55
 */

namespace app\common\model;


use app\common\exception\ParameterException;
use think\model\concern\SoftDelete;
use app\api\validate\mp\v1\User as ApiUserValidate;

class WeChatUser extends BaseModel
{
    protected $hidden = ['update_time','delete_time'];

    // 使用软删除
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function setNickNameAttr($value)
    {
        if (!empty($value)) {
            return base64_encode($value);
        }
        return $value;
    }

    public function getNickNameAttr($value)
    {
        if (!empty($value)) {
            return base64_decode($value);
        }
        return $value;
    }

    /**
     * 获取微信小程序用户的分页数据
     * @param array $params
     * @return \think\Paginator
     */
    public static function getPaginationList(array $params)
    {
        static::validatePaginationData($params);

        $static = new static();

        $static = $static->where('nick_name','<>','')
            ->order('create_time', 'desc');

        foreach ($params as $name => $value) {
            $value = trim($value);
            switch ($name) {
                case 'nick_name' :
                    if (!empty($value)) {
                        $likeText = "from_base64(nick_name) like '%{$value}%'";
                        $static = $static->whereRaw($likeText);
                    }
                    break;
                case 'phone_number' :
                    if (!empty($value)) {
                        $likeText = '%'.$value.'%';
                        $static = $static->whereLike('phone_number',$likeText);
                    }
                    break;
                case 'gender' :
                    if (!empty($value)) {
                        $static = $static->where('gender','=',intval($value));
                    }
                    break;
                case 'form':
                    if (!empty($value)) {
                        $static = $static->where('form','=',intval($value));
                    }
                    break;
                case 'sort_order':
                    if (!empty($value)) {
                        $static = $static->order($params['sort_prop'], $value == 'descending' ? 'desc' : 'asc');
                    }
                    break;
            }
        }

        return $static
            ->paginate([
                'page' => $params['page'],
                'list_rows' => $params['limit']
            ], false);
    }

    /**
     * 根据open_id添加用户
     * @param $open_id
     * @param int $status
     * @return mixed
     */
    public static function addUserWithOpenID($open_id, $status = 0)
    {
        $user = self::create([
            'openid' => $open_id,
            'status' => $status,
        ]);

        return $user->id;
    }

    /**
     * 更新用户的信息
     * @param array $data
     * @return bool
     */
    public static function updateUserInfo(array $data)
    {
        $validate = new ApiUserValidate();
        if (!$validate->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        $static = static::find($data['id']);

        $result = $static->allowField(['id','nick_name','avatar_url','gender','from'])
            ->save($data);

        if ($result !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新用户的Token对应的状态信息
     * @param array $data
     * @return bool
     */
    public static function updateUserTokenStatus(array $data)
    {
        foreach ($data as $name => $value) {
            switch($name) {
                case 'status' :
                    if (get_wx_config('mp_auth_user') == '开启') {
//                            (new UserToken(''))->updateUserTokenByUID($data['id'],'scope',((intval($value) == 1) ? ScopeEnum::USER : ScopeEnum::GUEST));
                    }

                    break;
                case 'third_status':
                    if (get_wx_config('mp_auth_third') == '开启') {
//                            (new UserToken(''))->updateUserTokenByUID($data['id'],'third_scope',((intval($value) == 1) ? ScopeEnum::USER : ScopeEnum::GUEST));
                    }
                    break;
            }
        }

    }
}